# -*- coding:utf-8 -*-
import wx 

# 导入gui工具生成的python文件 
import new_frame
import csv
fname = 'reg.csv'


class newFrame ( new_frame.newFrame):
    
    def __init__( self, parent ):
        new_frame.newFrame.__init__(self,parent) 
    def on_button_find( self, event ):
        csv=self.redcsv(self.m_text_name.GetValue())
        if csv['addr']>0:
            self.m_text_addr.SetValue(csv['addr'])
            self.m_text_reg.SetValue(csv['reg'])
            self.m_text_info.SetValue(csv['info'])
        event.Skip()

    def on_button_save( self, event ):
        csv={}
        csv['addr']=self.m_text_addr.GetValue()
        csv['reg']=self.m_text_reg.GetValue()
        csv['info']=self.m_text_info.GetValue()
        self.writecsv(self.m_text_name.GetValue(),csv)
        event.Skip()
        
    def redcsv(self, search):
    # 读取操作
        try:
            with open(fname,'rb') as csvfile:
                reader = csv.DictReader(csvfile)
                for row in reader:
                    if row['name']==search:
                        return row
                row['addr']=0
                return row
        except:
            row['addr']=0
            return ro
            
    def writecsv(self, search,writeinfo):
    # 存储操作
        tmp_row=[]
        try:
            with open(fname,'rb+') as csvfile:
                reader = csv.DictReader(csvfile)
                q=0
                for row in reader:
                    if row['name']==search:
                        row['addr']=writeinfo['addr']
                        row['reg']=writeinfo['reg']
                        row['info']=writeinfo['info']
                    tmp_row.append(row)
                    q=q+1
            with open("test.csv", 'wb') as f:
                w = csv.writer(f)
                fieldnames=tmp_row[0].keys()  # solve the problem to automatically write the header
                w.writerow(fieldnames)
                for row in tmp_row:
                    w.writerow(row.values())
            return 1
        except:
            return 0